package com.weacar.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.weacar.R;
import com.weacar.activity.CarDetailActivity;
import com.weacar.activity.MainActivity;
import com.weacar.adapter.AuctionSuccessAdapter;
import com.weacar.adapter.MessageCenterAdapter;
import com.weacar.adapter.TimeCountDownAdapter;
import com.weacar.adapter.TimeCountDownAuctionAdapter;
import com.weacar.bean.AuctionBean;
import com.weacar.bean.BaseBean;
import com.weacar.bean.CarBean;
import com.weacar.config.Constans;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.ToastUtil;
import com.weacar.utils.UserInfoUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class MyPriceFragment extends Fragment {


    private Unbinder unbinder;

    @BindView(R.id.tv_auction_doing)
    TextView tv_auction_doing;
    @BindView(R.id.tv_auction_success)
    TextView tv_auction_success;
    @BindView(R.id.v_ind_one)
    View v_ind_one;
    @BindView(R.id.v_ind_two)
    View v_ind_two;
    @BindView(R.id.rl_doing)
    RelativeLayout rl_doing;
    @BindView(R.id.rl_success)
    RelativeLayout rl_success;
    @BindView(R.id.lv_auction_doing)
    ListView lv_auction_doing;
    @BindView(R.id.lv_auction_success)
    ListView lv_auction_success;
    @BindView(R.id.iv_empty)
    ImageView iv_empty;
    @BindView(R.id.refresh_doing)
    SmartRefreshLayout refreshLayout_doing;
    @BindView(R.id.refresh_success)
    SmartRefreshLayout refreshLayout_success;

    public boolean refresh = false;
    public MainActivity mainActivity;


    // 竞拍中
    private List<AuctionBean.MsgBean> al;
    TimeCountDownAuctionAdapter timeCountDownAuctionAdapter;
    private int refresh_flag_doing = 0;
    // 竞拍成功记录
    private List<AuctionBean.MsgBean> al_success;
    AuctionSuccessAdapter auctionSuccessAdapter;
    private int refresh_flag_success = 0;

    private int page = 1;

    private boolean isAuction = true;


    @OnClick({R.id.tv_auction_doing, R.id.tv_auction_success})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.tv_auction_doing:
                if (!isAuction) {
                    page = 1;
                    al.clear();
                    getAuctionDoing();
                    isAuction = true;
                    v_ind_one.setVisibility(View.VISIBLE);
                    v_ind_two.setVisibility(View.GONE);
                    tv_auction_doing.setTextColor(ContextCompat.getColor(getContext(), R.color.mainOrg));
                    tv_auction_success.setTextColor(ContextCompat.getColor(getContext(), R.color.darkGrayText));
                    rl_doing.setVisibility(View.VISIBLE);
                    rl_success.setVisibility(View.GONE);
                }

                break;
            case R.id.tv_auction_success:
                if (isAuction) {
                    page = 1;
                    al_success.clear();
                    getAuctionSuccess();
                    isAuction = false;
                    v_ind_one.setVisibility(View.GONE);
                    v_ind_two.setVisibility(View.VISIBLE);
                    tv_auction_doing.setTextColor(ContextCompat.getColor(getContext(), R.color.darkGrayText));
                    tv_auction_success.setTextColor(ContextCompat.getColor(getContext(), R.color.mainOrg));
                    rl_doing.setVisibility(View.GONE);
                    rl_success.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    /**
     * 刷新竞拍中的数据
     */
    public void refreshDoingData() {
        page = 1;
        al.clear();
        getAuctionDoing();
    }


    /**
     * 获取竞拍中的数据
     */
    public void getAuctionDoing() {
        if (!NetWorkUtil.isNetworkAvailable(getActivity())) {
            ToastUtil.showShort(getContext(), "当前网络不可用");
            return;
        }

        if (UserInfoUtil.getToken(mainActivity).equals("")) {
            return;
        }

        try {
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.get_auction_ing);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("token", UserInfoUtil.getToken(mainActivity));
            js_request.put("page", String.valueOf(page));
            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    LogUtils.d("AuctionDoing_result = " + result);
                    if (refresh_flag_doing == 1) {
                        refreshLayout_doing.finishRefresh();
                    } else if (refresh_flag_doing == 2) {
                        refreshLayout_doing.finishLoadmore();
                    }
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null) {
                        try {
                            AuctionBean auctionBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), AuctionBean.class);
                            al.addAll(auctionBean.getMsg());
                            if (al.size() > 0) {
                                iv_empty.setVisibility(View.GONE);
                            } else {
                                iv_empty.setVisibility(View.VISIBLE);
                            }
                            timeCountDownAuctionAdapter = new TimeCountDownAuctionAdapter(al, mainActivity, mainActivity, MyPriceFragment.this);
                            lv_auction_doing.setAdapter(timeCountDownAuctionAdapter);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取竞拍成功的数据
     */
    public void getAuctionSuccess() {
        if (!NetWorkUtil.isNetworkAvailable(getActivity())) {
            ToastUtil.showShort(getContext(), "当前网络不可用");
            return;
        }

        if (UserInfoUtil.getToken(mainActivity).equals("")) {
            return;
        }
        try {
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.get_auction_success);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("token", UserInfoUtil.getToken(mainActivity));
            js_request.put("page", String.valueOf(page));
            params.setAsJsonContent(true);
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    LogUtils.d("AuctionSuccess_result = " + result);
                    if (refresh_flag_success == 1) {
                        refreshLayout_success.finishRefresh();
                    } else if (refresh_flag_success == 2) {
                        refreshLayout_success.finishLoadmore();
                    }
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null) {
                        try {
                            AuctionBean auctionBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), AuctionBean.class);
                            al_success.addAll(auctionBean.getMsg());
                            if (al_success.size() > 0) {
                                iv_empty.setVisibility(View.GONE);
                            } else {
                                iv_empty.setVisibility(View.VISIBLE);
                            }
                            auctionSuccessAdapter = new AuctionSuccessAdapter(al_success, mainActivity);
                            lv_auction_success.setAdapter(auctionSuccessAdapter);
                            lv_auction_success.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                    Intent intent = new Intent(mainActivity, CarDetailActivity.class);
                                    intent.putExtra("hidden", true);
                                    intent.putExtra("web_url", al_success.get(i).getWeb_url());
                                    startActivity(intent);
                                }
                            });


                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_my_price, null);
        unbinder = ButterKnife.bind(this, v);
        mainActivity = (MainActivity) getActivity();
        al = new ArrayList<>();
        al_success = new ArrayList<>();

        refreshLayout_doing.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                al.clear();
                page = 1;
                refresh_flag_doing = 1;
                getAuctionDoing();

            }
        });

        refreshLayout_doing.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page = page + 1;
                refresh_flag_doing = 2;
                getAuctionDoing();
            }
        });

        refreshLayout_success.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                al_success.clear();
                page = 1;
                refresh_flag_success = 1;
                getAuctionSuccess();

            }
        });

        refreshLayout_success.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page = page + 1;
                refresh_flag_success = 2;
                getAuctionSuccess();
            }
        });

        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isAuction) {
            // 获取竞拍中的数据
            al.clear();
            getAuctionDoing();
        } else {
            // 获取拍卖成功的数据
            al_success.clear();
            getAuctionSuccess();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }

        if (timeCountDownAuctionAdapter != null) {
            timeCountDownAuctionAdapter.cancelAllTimers();
        }
    }
}
